<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>关键问题5</title>
</head>
<body>
	<button onclick="demo()">点我发请求（3个请求依次发）</button>
  <script>
		function sendAjax(options){
				return new Promise((resolve,reject)=>{
					//获取请求相关的参数
					const {url,data} = options
					//创建xhr
					const xhr = new XMLHttpRequest()
					//绑定监听
					xhr.onreadystatechange = ()=>{
						if(xhr.readyState === 4 ){
							if(xhr.status >= 200 && xhr.status <= 299) resolve(xhr.response)
							else reject(xhr.response)
						}
					}
					//自动解析json
					xhr.responseType = 'json'
					let str = ''
					for (let key in data){
						str += `${key}=${data[key]}&`
					}
					str = str.slice(0,-1)
					//配置请求信息
					xhr.open('GET',url+'?'+str)
					//发送请求
					xhr.send()
				})
			}
		
		async function demo(){
			try {
				const result1 = await sendAjax({url:'https://api.apiopen.top/getJoke'})
				console.log('第1次请求成功了',result1)
				const result2 = await sendAjax({url:'https://api.apiopen.top/getJoke'})
				console.log('第2次请求成功了',result1)
				const result3 = await sendAjax({url:'https://api.apiopen.top/getJoke'})
				console.log('第3次请求成功了',result1)
			} catch (error) {
				console.log('请求出错',error)
			}
		}
		
		//验证一下then不写失败的回调会怎样
		/* new Promise((resolve,reject)=>{
			setTimeout(()=>{
				reject('a')
			},1000)
		})
		.then(
			value => {
				console.log('成功了1',value)
				return Promise.reject('b')
			},
			// reason => {throw reason} //对于then方法来说，如果程序员不写失败的回调，那么底层补全该行代码
		)
		.then(
			value => {console.log('成功了2',value)},
			reason => {console.log('失败了2',reason)}
		) */
		
	
	</script>
</body>
</html>